var ajaxBusy = false;
var focusId;
jQuery(function() {
	jsf.ajax.addOnEvent(statusUpdate);
	var compTitle = jQuery('#component_title').text();
	var correlationId = jQuery('#correlationId').val();
	jQuery('#navForm li a').each(
			function() {
				toggleUiStateActive(this, compTitle);
			}
	);
	jQuery('#headerForm button').each(
			function() {
				toggleUiStateActive(this, correlationId);
			}
	).mouseleave(function() {
		toggleUiStateActive(this, correlationId);
	});
	jQuery('#nav li a').hover(function() {
			jQuery(this).addClass("ui-state-hover");
		}, function() {
			jQuery(this).removeClass("ui-state-hover");
		}
	);
	jQuery(':input:not(input[type=hidden])','#mainForm').live('focus', function(){
		focusId = NovelFaces.jqId(this.id);
	}); 
});

function statusUpdate(data) {
	if (data.status == 'begin') {
		ajaxBusy = true;
		showOrHideAjaxLoading(true);
	} else {
		ajaxBusy = false;
		showOrHideAjaxLoading(false);
		if(data.status == 'success' && focusId){
			jQuery(focusId).focus();
			focusId = null;
		}
	}
}

function showOrHideAjaxLoading(showOrHide) {
	showOrHide ? jQuery("#mainForm").mask("Waiting...") : jQuery("#mainForm").unmask();
}

function toggleUiStateActive(element, value){
	$this = jQuery(element);
	$this.toggleClass('ui-state-active', $this.text() == value);
}